package main

import (
	"DataServer/common/logger"
	"DataServer/conf"
	"DataServer/db"
	"DataServer/logic"
	"DataServer/utils"
	"flag"
	"os"
	"runtime/pprof"
	"time"
)

func InitLogger(file string, lvl int) {
	logger.New(file, lvl, logger.Rotate{Size: logger.GB, Expired: time.Hour * 24 * 7, Interval: time.Hour * 24})
}

func waitFor(ch chan int, secs int) {
	if secs <= 0 {
		return
	}
	time.Sleep(time.Duration(secs) * time.Second)

	logger.Info("-------------ready to exit--------------------")
	ch <- 1
}

func main() {
	defer utils.PrintPanicStack()
	//init log
	filename := flag.String("conf_path", "../conf/dataserver.xml", "config file path")
	cpuprofile := flag.String("cpuprofile", "", "write cpu profile to file")
	logpath := flag.String("logpath", "../log/", "log file path")
	secs := flag.Int("exitsecs", 0, "how many secs to exit, defaut 0 to never exit")
	lvl := flag.Int("lvl", 6, "log level default -debug")
	flag.Parse()
	InitLogger(*logpath+"dataserver.log", *lvl)
	logger.Info("config file path:%v", *filename)

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			logger.Info("open cpu profile error:%v", err)
		} else {
			pprof.StartCPUProfile(f)
			defer pprof.StopCPUProfile()
		}
	}

	err := conf.LoadConf(*filename)
	if err != nil {
		logger.Info("error load conf fail:%v", err)
		return
	}
	logger.Info("load config file :%v success", *filename)

	err = db.InitMysql()
	if err != nil {
		logger.Info("error init mysql error :%v", err)
		return
	}

	go logic.InitRPCService()

	var ch chan int = make(chan int)
	go waitFor(ch, *secs)

	select {
	case _ = <-ch:
		logger.Info("---I'm done----")
		break
	}
}
